package com.itboye.textileexpres.myset;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.itboye.textileexpes.adapter.CityAndprovinceListAdapter;
import com.itboye.textileexpes.beans.CityBeans;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseActivity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.util.ListToStringUtil;
import com.itboye.textileexpres.util.SPContants;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.util.Utils;
import com.itboye.textileexpres.widget.MyListView;
import com.itboye.textileexpres.widget.XScrollView;
import com.itboye.textillexepres.db.DBManager;

/**
 * 城市列表
 * 
 * @author sy
 * 
 */
public class CishiCityActivity extends BaseActivity implements
		AMapLocationListener, OnClickListener {
	private BaseAdapter adapter;
	private MyListView country_lv_list;
	private Handler handler;
	private SQLiteDatabase database;
	private ArrayList<CityBeans> mCityNames;
	private ImageView back;
	EditText edit_inputcity;
	private XScrollView xsCrollView;
	private ArrayList<CityBeans> arrayLitArea;// 区域列表
	private DBManager dbManager;
	public String city;
	int type = 1;// 1、直辖市 2、城市
	boolean searchType = true;// true、根据 城市搜索店铺 false、根据地区搜索店铺
	RelativeLayout relypoutGps, locaridonRealyout;
	private TextView tvchina;
	String countryId;
	String titleName;
	private TextView tvTextCh;
	String strCh;
TextView title;
	CityBeans cityModel;

	TextView LocationResult;
	String from;
	// 高德定位
	ImageView img_other;
	private AMapLocationClient locationClient = null;
	private AMapLocationClientOption locationOption = null;
	private ListToStringUtil stringUtil;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.coogame_country;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		title.setText("地区选择");
		country_lv_list = (MyListView) findViewById(R.id.country_lv_list);
		cityModel = new CityBeans();
		strCh = getIntent().getStringExtra("strCh");
		System.out.println("全部地区" + strCh);
		tvTextCh.setText(strCh);
		img_other.setVisibility(View.GONE);
		dbManager = new DBManager(this);
		dbManager.openDateBase();
		from = getIntent().getStringExtra("from");
		// cityNoDBManager.openDateBase();
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		tvchina.setText(city);
		mCityNames = getCityNames();
		handler = new Handler();
		setAdapter(mCityNames);
		// 是scrollview显示在顶部
		xsCrollView.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				xsCrollView.scrollTo(0, 0);
			}
		});
		country_lv_list.setOnItemClickListener(new CityListOnItemClick());
		onGaoDeLalon();
	}

	public void onGaoDeLalon() {

		locationClient = new AMapLocationClient(this.getApplicationContext());
		locationOption = new AMapLocationClientOption();
		// 设置定位模式为高精度模式
		locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
		// 设置定位监听
		locationClient.setLocationListener(this);
		// 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
		locationOption.setInterval(Long.valueOf(1300));
		// 设置持续定位， true为单次定位
		locationOption.setOnceLocation(false);
		// 设置是否需要显示地址信息
		locationOption.setNeedAddress(true);
		/**
		 * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位 注意：只有在高精度模式下的单次定位有效，其他方式无效
		 */
		// locationOption.setGpsFirst(true);
		// 设置定位参数
		locationClient.setLocationOption(locationOption);

		// 启动定位
		locationClient.startLocation();
		mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);

	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			// 开始定位
			case Utils.MSG_LOCATION_START:
				LocationResult.setText("正在定位...");
				break;
			// 定位完成
			case Utils.MSG_LOCATION_FINISH:
				AMapLocation loc = (AMapLocation) msg.obj;
				// 获取返回的信息
				String result = Utils.getLocationStr(loc);

				// 返回兴趣点
				// String poi=Utils.getLocationPoi(loc);
				// 返回地址信息
				// String address = Utils.getLocationAddress(loc);
				SPUtils.put(CishiCityActivity.this, null,
						SPContants.COUNTRYNMAW, result);
				LocationResult.setText(result);
				break;
			// 停止定位
			case Utils.MSG_LOCATION_STOP:
				LocationResult.setText("定位停止");
				break;
			case R.id.LocationResult:
				if (LocationResult.getText().equals("定位失败")) {
					locationClient.startLocation();
					mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
				} else {

				}
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != locationClient) {
			/**
			 * 如果AMapLocationClient是在当前Activity实例化的，
			 * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
			 */
			locationClient.onDestroy();
			locationClient = null;
			locationOption = null;
		}
	}

	/**
	 * 从数据库获取城市数据
	 * 
	 * @return
	 */
	private ArrayList<CityBeans> getCityNames() {
		ArrayList<CityBeans> names = new ArrayList<CityBeans>();
		Cursor cursor = database.rawQuery(
				"SELECT * FROM common_country  ORDER BY country_name", null);

		while (cursor.moveToNext()) {

			CityBeans cityModel = new CityBeans();
			// 游标查询并赋值到CityBeans中
			cityModel.setCountry_name(cursor.getString(cursor
					.getColumnIndex("country_name")));
			cityModel.setId(cursor.getString(cursor.getColumnIndex("id")));

			cityModel.setCountryTelPrefix(cursor.getString(cursor
					.getColumnIndex("country_tel_prefix")));

			names.add(cityModel);
		}
		return names;
	}

	/**
	 * 城市列表点击事件
	 * 
	 * @author sy
	 * 
	 */
	class CityListOnItemClick implements OnItemClickListener {

		@SuppressWarnings("static-access")
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3) {

			searchType = true;
			cityModel = (CityBeans) country_lv_list.getAdapter().getItem(pos);
			city = cityModel.getCountry_name();
			cityModel.getCountryCode();

			String CityId = cityModel.getId();
			getPrivateNames(CityId);
			System.out.println("cityID" + cityModel.getId());
			SPUtils.put(CishiCityActivity.this, null, SpPublicParams.CountryID,
					CityId + "");

			finish();
			country_lv_list.setSelection(-1);// 设置选择项为第一项
		}

	}

	@SuppressWarnings("unused")
	private String getPrivateNames(String codeId) {
		System.out.println(">>>>>>>>>>>>>>" + codeId);
		ArrayList<CityBeans> names = new ArrayList<CityBeans>();
		Cursor cursor = database.rawQuery(
				"SELECT * FROM common_province where countryid=" + codeId
						+ " ORDER BY province", null);
		while (cursor.moveToNext()) {

			CityBeans cityModel = new CityBeans();
			cityModel.setCountry_name(cursor.getString(cursor
					.getColumnIndex("province")));

			cityModel.setId(cursor.getString(cursor
					.getColumnIndex("provinceID")));

			names.add(cityModel);
		}

		String country_tel = cityModel.getCountryTelPrefix();

		if (codeId.equals("1")) {
			Intent intent = new Intent(CishiCityActivity.this,
					ChinaIsCityAreaActivity.class);
			intent.putExtra("id", cityModel.getId());
			intent.putExtra("titlee", cityModel.getCountry_name());
			intent.putExtra("from", from);
			startActivity(intent);
		} else if (stringUtil.ListToString(names) == null
				|| stringUtil.ListToString(names).equals("")
				|| names.size() <= 0) {
			Intent intent2 = new Intent("City");
			intent2.putExtra("from", from);
			sendBroadcast(intent2);
			SPUtils.put(CishiCityActivity.this, null, SPContants.COUNTRYNMAW,
					city);
			SPUtils.put(CishiCityActivity.this, null,
					SPContants.CITYCOUNTRY_TEL_PREFIXUID, country_tel);

		} else {
			Intent intent = new Intent(CishiCityActivity.this,
					GetCityActivity.class);
			intent.putExtra("id", cityModel.getId());
			intent.putExtra("titlee", cityModel.getCountry_name());
			intent.putExtra("from", from);
			startActivity(intent);

			System.out.println("nullnull" + names.size());
		}
		return stringUtil.ListToString(names);
	}

	/**
	 * 为ListView设置适配器
	 * 
	 * @param list
	 */
	private void setAdapter(List<CityBeans> list) {

		if (list != null) {
			adapter = new CityAndprovinceListAdapter(this, list);
			country_lv_list.setAdapter(adapter);
		}

	}

	/***
	 * 跳转到中国区域
	 */

	public void onIntent() {
		Intent intent = new Intent(CishiCityActivity.this,
				ChinaIsCityAreaActivity.class);
		intent.putExtra("id", cityModel.getId());
		intent.putExtra("title", cityModel.getCountry_name());
		intent.putExtra("from", from);
		startActivity(intent);
	}

	@SuppressWarnings("static-access")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			this.finish();
			break;
		case R.id.relypoutGps:

			String CityId = cityModel.getId();
			System.out.println("cityID" + CityId);
			if (CityId == null) {
				Intent intent = new Intent(CishiCityActivity.this,
						ChinaIsCityAreaActivity.class);
				intent.putExtra("id", "1");
				intent.putExtra("title", "中国");
				intent.putExtra("from", from);
				startActivity(intent);
			} else if (CityId.equals("1")) {
				onIntent();
			} else if (!CityId.equals("1")) {
				Intent intent2 = new Intent("City");
				intent2.putExtra("from", from);
				sendBroadcast(intent2);
				SPUtils.put(CishiCityActivity.this, null,
						SPContants.COUNTRYNMAW, city);
				SPUtils.put(CishiCityActivity.this, null,
						SPContants.CITYCOUNTRY_TEL_PREFIXUID,
						cityModel.getCountry_name());

			} else {
				Intent intent = new Intent(CishiCityActivity.this,
						GetCityActivity.class);
				intent.putExtra("id", cityModel.getId());
				intent.putExtra("title", cityModel.getCountry_name());
				intent.putExtra("from", from);
				startActivity(intent);

			}
			finish();
			break;
		case R.id.locaridonRealyout:
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void onLocationChanged(AMapLocation arg0) {
		// TODO Auto-generated method stub
		if (null != arg0) {
			Message msg = mHandler.obtainMessage();
			msg.obj = arg0;
			msg.what = Utils.MSG_LOCATION_FINISH;
			mHandler.sendMessage(msg);
		}
	}

}